package com.example.cpl.myapplication;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.text.method.ScrollingMovementMethod;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
import java.sql.Date;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/*************************       66...... 连接      33......清零        99......断开          *************************/
public class View6 extends AppCompatActivity {
    //声明控件
    String filename6_1 = "MySharedString_View6_1", filename6_2 = "MySharedString_View6_2", filename6_3 = "MySharedString_View6_3";

    private String change() {
        switch (MainActivity.who) {
            case 1:
                return filename6_1;
            case 2:
                return filename6_2;
            case 3:
                return filename6_3;
            default:
                return null;
        }
    }

    int t;
    private static final String TAG = "TAG";
    private int wi = 0, bb = 0;
//    private EditText et1;
    private Button btn_clear, btn_save, btn_con, btn_cz;
    String check_km, check_cal;
    private TextView tv_km, tv_cal, tv_his;
    static Handler mHandler;
    static ExecutorService mThreadPool;
    static Socket socket;  // Socket变量
    static OutputStream outputStream;
    InputStream is;         // 输入流对象
    InputStreamReader isr; // 输入流读取器对象
    static BufferedReader br;     // 输入流读取器对象

    ProgressDialog m_pDialog;       //提示框变量

    public void initWidght() {
        btn_save = (Button) findViewById(R.id.btn_s1);
        btn_clear = (Button) findViewById(R.id.btn_c1);
        btn_con = (Button) findViewById(R.id.btn_con);
        btn_cz = (Button) findViewById(R.id.btn_cz);

        tv_km = (TextView) findViewById(R.id.tv_km);
        tv_cal = (TextView) findViewById(R.id.tv_cal);
        tv_his = (TextView) findViewById(R.id.tv_dat1);

    }
    void connect(){
    if(bb==0){
        btn_con.setText("连接中...");
        ProgressShow();


        new Thread() {              //开启耗时的子线程
            public void run() {
                Connect_WIFI_TCP("zxc", "zxc123456", 2, "192.168.4.1", 8080);
            }
        }.start();


    }
    else if(bb==1){
        bb=0;
        new Thread()
        {
            public void run(){


                try {

                    outputStream = socket.getOutputStream();
                    outputStream.write(("99999999999999999999"+"\n").getBytes("utf-8"));
                    outputStream.flush();

                    outputStream.close();       //输出流关闭
                    br.close();                 //输入流关闭

                    socket.close();             //断开TCP


                    Message msg=new Message();
                    bb=0;
                    msg.what=0x02;
                    mHandler.sendMessage(msg);


                } catch (IOException e){

                    e.printStackTrace();
                }
            }
        }.start();

    }
}

    public String read_SP_Str(String s, String s1, String file) {
        final SharedPreferences someData = getSharedPreferences(file, 0);
        return someData.getString("" + s + "", "" + s1 + "");
    }
    public int read_SP_Int(String s, int s1, String file) {
        final SharedPreferences someData = getSharedPreferences(file, 0);
        return someData.getInt("" + s + "", s1);
    }
    public void write_SP_Str(String s, String s1, String file) {
        final SharedPreferences someData = getSharedPreferences(file, 0);
        SharedPreferences.Editor editor = someData.edit();      //让文件 可以编辑
        editor.putString("" + s + "", "" + s1 + "");
        editor.commit();// 提交修改
    }
    public void write_SP_Int(String s, int s1, String file) {
        final SharedPreferences someData = getSharedPreferences(file, 0);
        SharedPreferences.Editor editor = someData.edit();      //让文件 可以编辑
        editor.putInt("" + s + "", s1);
        editor.commit();// 提交修改
    }
    public void clear_SP(String file) {
        final SharedPreferences someData = getSharedPreferences(file, 0);
        SharedPreferences.Editor editor = someData.edit();
        editor.clear();
        editor.commit();
    }
    public String getTime() {
        long time = System.currentTimeMillis();   //long now = android.os.SystemClock.uptimeMillis();
        SimpleDateFormat format = new SimpleDateFormat("MM-dd HH:mm");
        Date d1 = new Date(time);
        String t1 = format.format(d1);
        Log.d("TAG", t1);
        return t1;
    }

    @SuppressLint("SetTextI18n")
    private void setSP() {
        int i;
        t = read_SP_Int("参数", 0, change());
//        Log.d("TAG", "读取的参数t=" + "" + t + "");

        for (i = 1; i <= t; i++) {
            String km_his = read_SP_Str("公里数" + "" + i + "", "", change());
            String cal_his = read_SP_Str("卡路里" + "" + i + "", "", change());
            String tim_his = read_SP_Str("时间" + "" + i + "", "", change());
            tv_his.setText(tv_his.getText().toString() + "记录时间 " + "" + tim_his + "" + "\n距离 " + "" + km_his + "   " + "    卡路里 " + cal_his + "\n\n");
        }
    }

    public void ProgressShow() {               //  进度条提示框设置

        m_pDialog = new ProgressDialog(View6.this);         // 创建ProgressDialog对象
        m_pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); // 设置进度条风格，风格为长形
        m_pDialog.setTitle("提示"); // 设置ProgressDialog 标题
        m_pDialog.setMessage("正在连接 请等待...");                    // 设置ProgressDialog 提示信息
//        m_pDialog.setIcon(R.drawable.icon1);                      // 设置ProgressDialog 标题图标
//        m_pDialog.setMax(0);                                      // 设置进度条最大值
        m_pDialog.setIndeterminate(true);                        // 设置ProgressDialog 的进度条是否不明确
        m_pDialog.setCancelable(false);                             // 设置ProgressDialog 是否可以按退回按键取消
        m_pDialog.show();                                            // 让ProgressDialog显示
    }

    public void Connect_WIFI_TCP(String ssid, String password, int type, final String ip, final int port) { //连接WiFi 并连接TCP
        Log.d(TAG, "WiFi连接中...");
        WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE); //申请WiFi服务
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();

        WifiAdmin wifiAdmin = new WifiAdmin(View6.this);

        ConnectivityManager connManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);//定义一个可以判断WiFi是否连接上的布尔型变量
        NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);                 //同上

        if (!(mWifi.isConnected()) || (!(wifiInfo.getSSID().equals("\"" + ssid + "\"")))) { //ssid为WiFi名
            if (wifiInfo.getSSID().equals("<unknown ssid>")) {    //这个条件说明没有打开WiFi
                wifiAdmin.openWifi();
            }
            wifiAdmin.disconnectWifi(wifiAdmin.getNetworkId()); //断开当前连接的WiFi
            wifiAdmin.addNetwork(wifiAdmin.createWifiConfig("" + ssid + "", "" + password + "", type)); //WiFi信息

            Log.d(TAG, "延时开始");
            try {
                Thread.sleep(3500);         //这里加延时3.5秒
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            Log.d(TAG, "延时结束");

            Log.d(TAG, "判断WiFi是否连接");
            if ((wi < 2) && ((!wifiInfo.getSSID().equals("\"" + ssid + "\"")) || (!(mWifi.isConnected())))) {
                wi++;
                Log.d(TAG, "WiFi连接失败 尝试重新连接.....");
                Log.d(TAG, "WiFi重新连接次数" + wi);
                Connect_WIFI_TCP("" + ssid + "", "" + password + "", type, "" + ip + "", port);

            }
            if (wi == 2) {
                Message msg = new Message();
                msg.what = 0x04;
                mHandler.sendMessage(msg);
            }
            wi = 0;
        }
        if ((wifiInfo.getSSID().equals("\"" + ssid + "\"")) && (mWifi.isConnected())) {
            Log.d(TAG, "WiFi连接成功!");
//            Message msg=new Message();
//            msg.what=0x02;
//            mHandler.sendMessage(msg);
            Connect_Tcp("" + ip + "", port);

        }
        else {

            Message msg = new Message();
            msg.what = 0x02;      //button 变成“连接”
            mHandler.sendMessage(msg);
            Log.d(TAG, "——WiFi:  " + ssid + "  没有找到........0.0");
        }
    }
    public void Connect_Tcp(final String ip, final int port) {
        Log.d(TAG, "TCP连接中...");
        try {
            socket = new Socket("" + ip + "", port);        //创建一个TCP连接

            Log.d(TAG, "TCP连接成功");

            is = socket.getInputStream();             // 步骤1：创建输入流对象InputStream
            isr = new InputStreamReader(is);          // 步骤2：创建输入流读取器对象 并传入输入流对象
            br = new BufferedReader(isr);             // 该对象作用：接收输入流数据到缓冲区

            outputStream = socket.getOutputStream();  // 配置输出流。步骤：写入需要发送的数据到输出流对象中
            outputStream.write(("666666666666666666666"+"\n").getBytes("utf-8"));    // 输出流。数据的结尾加上换行符才可让服务器端的readline()停止阻塞

            Log.d(TAG, "——握手自行车中");
//               outputStream.write(("start" +wi+ "\n").getBytes("utf-8"));    //可以发送int类型的
            // 步骤3：发送数据到服务端
            outputStream.flush();       //发送完毕
            Log.d(TAG, "TCP数据发送成功");
            bb = 1;     //bb=1 表示连接成功  bb=0 表示连接失败

            Message msg = new Message();
            msg.what = 0x03; //这里判断是否连接成功 0x03让按钮显示为断开
            mHandler.sendMessage(msg);



            String rec = null;      // 接收下位机发送过来的消息

            while((rec = br.readLine()) != null) {      //判断是否接收到数据
                Log.d(TAG, "TCP接收的数据为："+rec);

                msg = new Message();
                msg.what = 0x01;    //标识：用来状态判断
                msg.obj = rec;      //把接收到的字符串 赋值给msg.obj

                mHandler.sendMessage(msg);
            }

        } catch (IOException e) {           //抛出错误

            Message msg = new Message();
            msg.what = 0x02;            //发送消息 让按钮复位 显示（连接）
            mHandler.sendMessage(msg);

            Log.d(TAG, "TCP连接失败......0.0");

            e.printStackTrace();
        }

//            }
//        });
    }

    @SuppressLint({"HandlerLeak", "SetTextI18n"})
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_view6);
        initWidght(); //关联
        tv_his.setMovementMethod(ScrollingMovementMethod.getInstance());
        setSP();
        Log.d(TAG, "距离 =" + read_SP_Str("距离","0",change()));


        int i=Integer.parseInt(read_SP_Str("距离","0",change()));
        double k= 1.8*i;
        double ca= 0.126*i;
        DecimalFormat decimalFormat = new DecimalFormat("0.00");        //格式化为2个小数点
        String k1=decimalFormat.format(k);
        String ca1=decimalFormat.format(ca);
        tv_km.setText(""+k1+"");//距离
        tv_cal.setText(""+ca1+"");
//        tv_km.setText(read_SP_Str("距离","0",change()));
//        tv_cal.setText( ""+ 0.1*c + "" );        //0.07*1.8*c
//        tv_cal.setText(""+0.1*(Integer.parseInt(tv_km.getText().toString()))+"");

        mThreadPool = Executors.newCachedThreadPool();   // 初始化线程池

        mHandler = new Handler() {                 // 实例化主线程,用于更新接收过来的消息 ，然后更新主线程UI
            @SuppressLint("SetTextI18n")
            @Override
            public void handleMessage(android.os.Message msg) {
                Log.d(TAG, "接收的obj= " + msg.obj);
                Log.d(TAG, "接收的what= " + msg.what);
                switch (msg.what) {
                    case 0x01:  //连接成功 并收到数据

                        int c=Integer.parseInt(msg.obj.toString()); //obj强制转换成成string ，再强制转换数值类型int

                        double k= 1.8*c;
                        double ca= 0.126*c;
                        DecimalFormat decimalFormat = new DecimalFormat("0.00");//格式化
                        String k1=decimalFormat.format(k);
                        String ca1=decimalFormat.format(ca);

                        tv_km.setText(""+k1+"");//距离
//                        tv_km.setText(msg.obj.toString());
//                        int intsg = Integer.parseInt(tv_km.getText().toString());
//                        int km= Integer.parseInt(msg.obj.toString());
//                        int cal=70*km;      //写到这里了
                        tv_cal.setText( ""+ ca1 + "" );        //0.07*1.8*c
//                        Log.d(TAG, "cal= " +""+ca1 + "");
                        write_SP_Str("距离",""+msg.obj.toString()+"",change());
                        break;

                    case 0x02:              //  连接失败
                        m_pDialog.cancel();     //关闭进度条对话框
                        btn_con.setText("连接");
                        break;

                    case 0x03:          //连接成功 没有收到数据
                        m_pDialog.cancel();     //关闭进度条对话框
                        btn_con.setText("断开");
                        break;

                    case 0x04:              //连接失败
                        m_pDialog.cancel();     //关闭进度条对话框

                        AlertDialog dlg = new AlertDialog.Builder(View6.this)
//                                .setIcon(R.drawable.icon1)
                                .setTitle("连接状态")
                                .setMessage("没有找到自行车！请重试")
                                .setPositiveButton("确定", null)
                                .create();
                        dlg.show();
                        break;
                }

            }
        };
        btn_save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String km = null;
                km = tv_km.getText().toString();
                String cal = null;
                cal = tv_cal.getText().toString();

                if (!km.equals("0.00") && !cal.equals("0.00")) {
                    if (!km.equals(check_km) || !cal.equals(check_cal)) {

                        t = t + 1;
                        String time = getTime();
                        tv_his.setText(tv_his.getText().toString() + "记录时间 " + "" + time + "" + "\n距离 " + "" + tv_km.getText().toString() + "" + "       卡路里 " + "" + tv_cal.getText().toString() + "\n\n");

                        int offset = tv_his.getLineCount() * tv_his.getLineHeight();        //自动跳到最后一行
                        if (offset > tv_his.getHeight()) {
                            tv_his.scrollTo(0, offset - tv_his.getHeight());
                        }

                        write_SP_Str("公里数" + "" + t + "", tv_km.getText().toString(), change());
                        write_SP_Str("卡路里" + "" + t + "", tv_cal.getText().toString(), change());
                        write_SP_Str("时间" + "" + t + "", getTime(), change());
                        write_SP_Int("参数", t, change());

                        check_km = km;
                        check_cal = cal;

                        Toast.makeText(getApplicationContext(), "记录成功", Toast.LENGTH_SHORT)
                                .show();//阴影提示框

                    } else {
                        Toast.makeText(getApplicationContext(), "已记录", Toast.LENGTH_SHORT)
                                .show();//阴影提示框
                    }
                } else {
                    Toast.makeText(getApplicationContext(), "无数据", Toast.LENGTH_SHORT)
                            .show();//阴影提示框


                }
            }
        });
        btn_cz.setOnClickListener(new View.OnClickListener()        //清零按钮
        {
            @Override
            public void onClick(View view)
            {
                if (bb == 1) {
                    new Thread() {
                        public void run() {


                            try {
                                outputStream = socket.getOutputStream();
                                outputStream.write(("33333333333333333333"+"\n").getBytes("utf-8"));
                                outputStream.flush();


                                write_SP_Str("距离","0",change());


                            } catch (IOException e) {

                                Toast.makeText(getApplicationContext(), "连接错误", Toast.LENGTH_SHORT)
                                        .show();//阴影提示框
                                //如果没有成功发送
                                e.printStackTrace();
                            }
                        }
                    }.start();

                    tv_km.setText("0.00");
                    tv_cal.setText("0.00");

                    Toast.makeText(getApplicationContext(), "已清零", Toast.LENGTH_SHORT)
                            .show();//阴影提示框
                }
                else
                {
                    Toast.makeText(getApplicationContext(), "未连接自行车", Toast.LENGTH_SHORT)
                            .show();//阴影提示框


                }
            }
        });
        btn_clear.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View view)
            {
//                tv_km.setText(""+0+"");
//                tv_cal.setText(""+0+"");
                tv_his.setText("");

                clear_SP(change());
                t=0;
                check_km=null;
                check_cal=null;

                Toast.makeText(getApplicationContext(), "已清空历史", Toast.LENGTH_SHORT)
                        .show();//阴影提示框
            }
        });

        btn_con.setOnClickListener(new View.OnClickListener()       //连接按钮
        {
            @Override
            public void onClick(View view)
            {
                connect();
               // Log.d(TAG,"输入的机器号为："+""+et_id.getText().toString()+"");
//                if(bb==0)
//                {
//                    btn_con.setText("连接中...");
//                    ProgressShow();
//                    new Thread() {
//                        public void run() {
//                            Connect_WIFI_TCP("zxc", "zxc123456", 2, "192.168.4.1", 8080);
//                        }
//                    }.start();
//                }
//                else if(bb==1)
//                {
//                    bb=0;
//                    new Thread()
//                    {
//                        public void run(){
//                            try {
//                                outputStream = socket.getOutputStream();
//                                outputStream.write(("99999999999999999999"+"\n").getBytes("utf-8"));
//                                outputStream.flush();
//                                outputStream.close();
//                                br.close();
//
//                                socket.close();             //断开TCP
//                                Message msg=new Message();
//                                bb=0;
//                                msg.what=0x02;
//                                mHandler.sendMessage(msg);
//                            } catch (IOException e){
//                                e.printStackTrace();
//                            }
//                        }
//                    }.start();
//                }
            }
        });
//        connect();
    }
@Override
protected void onRestart() {
    super.onRestart();
}
    @SuppressLint("PrivateResource")



    @Override
    public void onBackPressed() {       //重写back按键
        super.onBackPressed();

        wi=0;
        if(bb==1)
        {
            new Thread()
            {
                public void run(){
                    try {
                        outputStream = socket.getOutputStream();
                        outputStream.write(("99999999999999999999"+"\n").getBytes("utf-8"));
                        outputStream.flush();
                        outputStream.close();
                        br.close();
                        socket.close();             //断开TCP
                        Message msg=new Message();
                        bb=0;
                        msg.what=0x02;
                        mHandler.sendMessage(msg);
                    } catch (IOException e) {

                        e.printStackTrace();
                    }
                }
            }.start();
        }
//        System.out.println("按下了back返回键，变量清零");
        return;
    }
}